package com.jjc.android.fragment

import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.os.Bundle
import android.view.View
import android.view.animation.OvershootInterpolator
import android.widget.LinearLayout
import android.widget.TextView
import androidx.core.content.ContextCompat
import androidx.lifecycle.MutableLiveData
import androidx.viewpager.widget.ViewPager
import androidx.viewpager.widget.ViewPager.SimpleOnPageChangeListener
import com.jjc.android.Constants
import com.jjc.android.GlobalManager
import com.jjc.android.R
import com.jjc.android.UserManager
import com.jjc.android.activity.AddTestedPersonActivity
import com.jjc.android.activity.MyDeviceActivity
import com.jjc.android.activity.TestedPersonListActivity
import com.jjc.android.adapter.SimpleFragmentPagerAdapter
import com.jjc.android.base.BaseLazyLoadFragment
import com.jjc.android.dialog.AttachListDialog
import com.jjc.android.dialog.BindDeviceDialog
import com.jjc.android.entity.*
import com.jjc.android.net.SimpleHttpCallback
import com.jjc.android.util.*
import com.jjc.android.view.CommonKt.appendDeviceName
import com.jjc.android.view.ScaleTransitionPagerTitleView
import com.jjc.android.view.formatTwo
import com.jjc.android.view.isShow
import com.jjc.android.view.layout.drawable_end
import com.jjc.android.view.onClick
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.enums.PopupPosition
import com.lzy.okgo.OkGo
import io.reactivex.Observable
import net.lucode.hackware.magicindicator.FragmentContainerHelper
import net.lucode.hackware.magicindicator.MagicIndicator
import net.lucode.hackware.magicindicator.buildins.UIUtil
import net.lucode.hackware.magicindicator.buildins.commonnavigator.CommonNavigator
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.CommonNavigatorAdapter
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerIndicator
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerTitleView
import net.lucode.hackware.magicindicator.buildins.commonnavigator.indicators.LinePagerIndicator
import net.lucode.hackware.magicindicator.buildins.commonnavigator.titles.ColorTransitionPagerTitleView
import net.lucode.hackware.magicindicator.buildins.commonnavigator.titles.SimplePagerTitleView
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import kotlin.properties.Delegates

class HomeFragment : BaseLazyLoadFragment(){

    companion object{
        fun newInstance():HomeFragment{
            val fragment = HomeFragment()
            fragment.setInflateLazy(true)
            return fragment
        }
    }

    private lateinit var viewPager: ViewPager
    private lateinit var magicIndicator: MagicIndicator
    private lateinit var homeToolbar: LinearLayout
    private lateinit var addUserBtn: TextView
    private lateinit var deviceBtn:TextView

    override fun getLayoutId(): Int = R.layout.fragment_home

    override fun initView(view: View) {
        super.initView(view)
        initViews(view)
    }

    private fun initViews(view: View) {
        deviceBtn = view.findViewById(R.id.deviceBtn)
        addUserBtn = view.findViewById(R.id.addUserBtn)
        homeToolbar = view.findViewById(R.id.homeToolbar)
        magicIndicator = view.findViewById(R.id.magicIndicator)
        viewPager = view.findViewById(R.id.viewPager)
        val contentLayout:View = view.findViewById(R.id.contentLayout)
        UIStatusBarHelper.setStatusBarPaddingAndHeight(homeToolbar)

        deviceBtn.onClick {
            if(deviceList.isNullOrEmpty()){
                startActivity(Intent(requireContext(),MyDeviceActivity::class.java))
            }else{
                AttachListDialog<DeviceDto>(deviceBtn)
                    .contentList(deviceList)
                    .onItemClick { position, value ->
                        currentDevice = value
                    }
                    .build()
                    .show()
            }

        }
        addUserBtn.onClick {
            if(testedPersonList.isNullOrEmpty()){
                startActivity(Intent(requireContext(),TestedPersonListActivity::class.java))
            }else{
                AttachListDialog<TestedPersonDto>(addUserBtn)
                    .contentList(testedPersonList)
                    .onItemClick { position, value ->
                        if(value == addTesterMode){
                            startActivity(Intent(requireContext(),AddTestedPersonActivity::class.java))
                        }else{
                            currentTester = value
                        }

                    }
                    .build()
                    .show()
            }
        }
        showLoadingView(contentLayout)

        fetchPageInfo()
    }


    override fun fetchPageInfo() {
        fetchTesterData()
        fetchDevices()
    }

    override fun onFragmentResume(firstResume: Boolean) {
        super.onFragmentResume(firstResume)
        fetchClassifies()
        fetchDevices()
    }
    private val oldPrimaryClassifies:ArrayList<PrimaryClassifyDto> = ArrayList()

    private fun isSameData(data:List<PrimaryClassifyDto>?):Boolean{
        if(oldPrimaryClassifies.size!=data?.size) return false
        data.forEachIndexed { index, primaryClassifyDto ->
            if(oldPrimaryClassifies[index].id!=primaryClassifyDto.id){
                return false
            }
            if(oldPrimaryClassifies[index].yzozfiekal0pbsij!=primaryClassifyDto.yzozfiekal0pbsij){
                return false
            }
        }
        return true
    }

    private fun fetchClassifies(){
        OkGo.post<LzyResponse<PageInfo<PrimaryClassifyDto>>>(Constants.getFormList)
            .paramEx(mutableMapOf(
                "page" to 1,
                "pagesize" to 100,
                "needpage" to "1",
                "formheaduuid" to "4a8b2701a8c14cf486805aead608ac0e",
                "isasc" to false,
                "sortid" to "by4aahapyxw1kvwb",
                "filters" to listOf<KeyValuePair>(
                    KeyValuePair("2vygl9fewacmgfww","5e1e309a-abaf-45f2-a030-4b20e42a664f"),
                    KeyValuePair("sjxfveecowhxayym",MultiLanguageUtil.getInstance().getValue("f8665d63-dc7f-4047-919f-b201ddadde05","76329d9d-b7d8-4306-82a6-9933f2a5e4b3"))
                )),true)
            .tag(this)
            .execute(object : SimpleHttpCallback<LzyResponse<PageInfo<PrimaryClassifyDto>>>(false){
                override fun onCallSuccess(response: LzyResponse<PageInfo<PrimaryClassifyDto>>) {
                    if(!response.data?.data.isNullOrEmpty()){
                        hideLoadingView()
                        if(!isSameData(response.data.data)){
                            oldPrimaryClassifies.clear()
                            oldPrimaryClassifies.addAll(response.data.data)
                            initMagicIndicator(response.data.data)
                        }
                    }else{
                        showEmptyView(getString(R.string.no_cate_txt))
                    }

                }

                override fun onCallError(error: String?) {
                    super.onCallError(error)
                    showErrorView(error)
                }
            })
    }

    private val deviceList = ArrayList<DeviceDto>()
    var currentDevice:DeviceDto? by Delegates.observable(null){_,old,new->
        if(new==null){
            deviceBtn.setCompoundDrawablesWithIntrinsicBounds(R.mipmap.home_nav_shebei,0,0,0)
            deviceBtn.text = getString(R.string.device_txt)
        }else{
            deviceBtn.setCompoundDrawablesWithIntrinsicBounds(R.mipmap.home_nav_shebei,0,R.mipmap.tuya_nav_icon_down,0)
            deviceBtn.text = new.provideText()
        }
    }

    private val bindDeviceDialog:BindDeviceDialog by lazy {
        BindDeviceDialog(requireContext()).also {
            XPopup.Builder(requireContext())
                .dismissOnBackPressed(false)
                .dismissOnTouchOutside(false)
                .asCustom(it)
        }
    }


    private fun fetchDevices(){
        OkGo.post<LzyResponse<PageInfo<DeviceDto>>>(Constants.getFormList)
            .paramEx(mutableMapOf(
                "page" to 1,
                "pagesize" to Int.MAX_VALUE,
                "needpage" to "1",
                "isasc" to true,
                "sortid" to "created_at",
                "formheaduuid" to "2582bc4c14914246807a26886f46dd0e","filters" to listOf<KeyValuePair>(
                KeyValuePair("ope0wk2ysioftswt",UserManager.userId())
            )),true)
            .tag(this)
            .execute(object : SimpleHttpCallback<LzyResponse<PageInfo<DeviceDto>>>(false){
                override fun onCallSuccess(response: LzyResponse<PageInfo<DeviceDto>>) {
                    deviceList.clear()
                    if(response.data?.data.isNullOrEmpty()){
                        bindDeviceDialog.show()
                    }else{
                        if(bindDeviceDialog.isShow){
                            bindDeviceDialog.dismiss()
                        }
                        deviceList.addAll(response.data.data.appendDeviceName())
                    }
                    if(!deviceList.isNullOrEmpty()){
                        var isChange = true
                        if(currentDevice!=null){
                            isChange = deviceList.find { it.id == currentDevice?.id}.let {
                                if(it!=null){
                                    currentDevice = it
                                }
                                it==null
                            }
                        }
                        if(isChange){
                            currentDevice = deviceList[0]
                        }
                    }else{
                        currentDevice = null
                    }
                }

            })
    }

    var currentTester:TestedPersonDto? by Delegates.observable(null){_,old,new->
        currentTesterLive.postValue(new)
        if(new==null){
            addUserBtn.setCompoundDrawablesWithIntrinsicBounds(R.mipmap.home_nav_tianjia_1,0,0,0)
            addUserBtn.text = getString(R.string.un_add_txt)
        }else{
            addUserBtn.setCompoundDrawablesWithIntrinsicBounds(R.mipmap.home_nav_tianjia_1,0,R.mipmap.tuya_nav_icon_down,0)
            addUserBtn.text = new.provideText()
        }
    }
    private val currentTesterLive:MutableLiveData<TestedPersonDto> = MutableLiveData(currentTester)
    private val addTesterMode: TestedPersonDto by lazy {
        TestedPersonDto().apply {
            jsonMember8pa55qzbspju5tzn = getString(R.string.newly_add_txt)
            id = "-1"
        }
    }
    private val testedPersonList = ArrayList<TestedPersonDto>()
    private fun fetchTesterData(){
        OkGo.post<LzyResponse<PageInfo<TestedPersonDto>>>(Constants.getFormList)
            .paramEx(mutableMapOf(
                "page" to 1,
                "pagesize" to 100,
                "needpage" to 0,
                "formheaduuid" to "83ed64e98f6c4edbaf7b388d7691e57b",
                "filters" to listOf<KeyValuePair>(
                    KeyValuePair("61xugqtzoyid5pw2",UserManager.userId())
                )),true)
            .tag(this)
            .execute(object : SimpleHttpCallback<LzyResponse<PageInfo<TestedPersonDto>>>(false){
                override fun onCallSuccess(response: LzyResponse<PageInfo<TestedPersonDto>>) {
                    response.data?.data.let {
                        testedPersonList.clear()
                        if(!it.isNullOrEmpty()){
                            testedPersonList.addAll(it)
                        }
                        testedPersonList.add(addTesterMode)
                    }
                    if(!testedPersonList.isNullOrEmpty()&&testedPersonList.size>1){
                        var isChange = true
                        if(currentTester!=null){
                            isChange = testedPersonList.find { it.id == currentTester?.id}.let {
                                if(it!=null){
                                    currentTester = it
                                }
                                it==null
                            }
                        }
                        if(isChange){
                            currentTester = testedPersonList[0]
                        }
                    }else{
                        currentTester = null
                    }
                    fetchLastRecord()
                }

                override fun onCallError(error: String?) {
                    super.onCallError(error)
                }
            })
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onMessageEvent(event: ChangeTesterEvent){
        fetchTesterData()
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onMessageEvent2(event: ChangeDeviceEvent){
        fetchDevices()
    }

    override fun isHaveEventBus(): Boolean {
        return true
    }
    private var isFirstComeInPage = true
    private fun fetchLastRecord(){
        if(!isFirstComeInPage||currentTester==null||oldPrimaryClassifies.isNullOrEmpty()) return
        isFirstComeInPage = false

        OkGo.post<LzyResponse<LastRecordDto>>(Constants.getOneMinorTermDetails)
            .paramEx(mutableMapOf(
                "tuoTuUserId" to UserManager.userId(),
                "tuoTuToken" to UserManager.userInfo().tuoTuToken,
                "detectionUserId" to currentTester?.id))
            .tag(this)
            .execute(object : SimpleHttpCallback<LzyResponse<LastRecordDto>>(false){
                override fun onCallSuccess(response: LzyResponse<LastRecordDto>) {
                    val findPrimaryClassifyId:String? = response.data?.firstMinorTermId
                    val findSecondaryClassifyId:String? = response.data?.minorTermId
                    oldPrimaryClassifies.forEachIndexed { index, primaryClassifyDto ->
                        if(findPrimaryClassifyId.isNullOrEmpty()){
                            if(!primaryClassifyDto.yzozfiekal0pbsij.isNullOrEmpty()&&primaryClassifyDto.yzozfiekal0pbsij.contains(getString(R.string.man_bing_txt))){
                                viewPager.currentItem = index
                                ((viewPager.adapter as? SimpleFragmentPagerAdapter)
                                    ?.fragments?.get(index) as? HomeChildFragment)
                                    ?.updateDefaultPage("")
                                return@forEachIndexed
                            }
                        }else{
                            if(primaryClassifyDto.id == findPrimaryClassifyId){
                                viewPager.currentItem = index
                                ((viewPager.adapter as? SimpleFragmentPagerAdapter)
                                    ?.fragments?.get(index) as? HomeChildFragment)
                                    ?.updateDefaultPage(findSecondaryClassifyId?:"")
                                return@forEachIndexed
                            }
                        }
                    }
                }
            })




    }

    private fun initMagicIndicator(tab:List<PrimaryClassifyDto>?) {
        if(tab.isNullOrEmpty()) return
        val fragments = tab.map { HomeChildFragment.newInstance(it.id).also {fragment->
            currentTesterLive.observe(fragment,fragment)
        } }
        viewPager.adapter = SimpleFragmentPagerAdapter(childFragmentManager, fragments)
        viewPager.offscreenPageLimit = tab.size
        val commonNavigator = CommonNavigator(requireContext())
        commonNavigator.isAdjustMode = true
        commonNavigator.adapter = object : CommonNavigatorAdapter() {
            override fun getCount(): Int {
                return tab.size
            }

            override fun getTitleView(context: Context, index: Int): IPagerTitleView {
                val simplePagerTitleView = ScaleTransitionPagerTitleView(context)
                simplePagerTitleView.minScale = 1f
                simplePagerTitleView.normalColor = ContextCompat.getColor(requireContext(),R.color.c_666666)
                simplePagerTitleView.selectedColor = ContextCompat.getColor(requireContext(),R.color.c_333333)
                simplePagerTitleView.text = tab[index].yzozfiekal0pbsij
                simplePagerTitleView.setOnClickListener { viewPager.currentItem = index }
                simplePagerTitleView.textSize = 16f
                return simplePagerTitleView
            }

            override fun getIndicator(context: Context): IPagerIndicator {
                val linePagerIndicator = LinePagerIndicator(context)
                linePagerIndicator.mode = LinePagerIndicator.MODE_EXACTLY
                linePagerIndicator.lineWidth = 27f.dp2px.toFloat()
                linePagerIndicator.lineHeight = 4f.dp2px.toFloat()
                linePagerIndicator.roundRadius = 2f.dp2px.toFloat()
                linePagerIndicator.setColors(ContextCompat.getColor(requireContext(),R.color.c_831cb5))
                return linePagerIndicator
            }
        }
        magicIndicator.navigator = commonNavigator

        val fragmentContainerHelper = FragmentContainerHelper(magicIndicator)
        fragmentContainerHelper.setInterpolator(OvershootInterpolator(2.0f))
        fragmentContainerHelper.setDuration(300)
        viewPager.addOnPageChangeListener(object : SimpleOnPageChangeListener() {
            override fun onPageSelected(position: Int) {
                fragmentContainerHelper.handlePageSelected(position)
            }
        })
        fetchLastRecord()
    }

}